<template>
	<div class="data-screen" ref="dataScreenRef">
		<slot></slot>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, toRefs } from 'vue';

const props = withDefaults(
	defineProps<{
		screenWidth?: number;
		screenHeight?: number;
	}>(),
	{
		screenWidth: 1920,
		screenHeight: 1080
	}
);

const { screenWidth, screenHeight } = toRefs(props);

const dataScreenRef = ref<HTMLElement | null>(null);
/* 根据浏览器大小推断缩放比例 */
const getScale = (width = 1920, height = 1080): number => {
	const ww = window.innerWidth / screenWidth.value ?? width;
	const wh = window.innerHeight / screenHeight.value ?? height;
	return ww < wh ? ww : wh;
};

/* 浏览器监听 resize 事件 */
const resize = () => {
	if (dataScreenRef.value) {
		dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
	}
	// 使用了 scale 的echarts其实不需要需要重新计算缩放比例
	// Object.values(dataScreen).forEach(chart => {
	// 	chart && chart.resize();
	// });
};

onMounted(() => {
	if (dataScreenRef.value) {
		dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
		dataScreenRef.value.style.width = `${screenWidth.value}px`;
		dataScreenRef.value.style.height = `${screenHeight.value}px`;
	}
	window.addEventListener('resize', resize);
});

/* 销毁时触发 */
onBeforeUnmount(() => {
	window.removeEventListener('resize', resize);
});
</script>

<style scoped lang="scss">
.data-screen {
	position: fixed;
	top: 50%;
	left: 50%;
	z-index: 999;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	transition: all 0.3s;
	transform-origin: left top;
}
</style>
